﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web;
using System.Reflection;

namespace WebFabricator.org
{
    /// <summary>
    /// The Fabric is the glue that holds the entire system together providing the facilities necessary to process a request
    /// </summary>
    [Namespace(typeof(WebFabric<>))]
    public class WebFabric<T> : List<IValueProvider>, IWebFabric<T>
    {

        public WebFabric(T context)
            : base()
        {
            Context = context;
            Application.ValueProviders.ForEach(factory => this.Add(factory.CreateValueProvider<T>(this)));
        }

        // Summary:
        //     Gets information about the HTTP request.
        //
        // Returns:
        //     An object that contains information about the HTTP request.
        public virtual T Context 
        { 
            get; 
            private set; 
        }

        public bool ContainsPrefix(string prefix)
        {
           return this.DefaultIfEmpty(null).FirstOrDefault(valueprovider =>
            {
                return valueprovider.ContainsPrefix(prefix);

            }) != null;
        }

        public IValueProviderResult GetValue(string key)
        {
            return this
                .Where(valueprovider => valueprovider != null && valueprovider.ContainsPrefix(key))
                .DefaultIfEmpty(null)
                .Select(valueprovider => valueprovider == null? null : valueprovider.GetValue(key))
                .Single();
            
        }

    }
}
